<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理</title>
    <!-- 引入Element UI的样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        .container {
            height: 98vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .fixed-header {
            position: sticky;
            top: 0;
            background: white;
            z-index: 1000;
            padding-bottom: 10px;
            border-bottom: 1px solid #e0e0e0;
        }

        .fixed-footer {
            position: sticky;
            bottom: 0;
            background: white;
            z-index: 1000;
            padding: 10px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: center;
        }

        .content {
            flex: 1;
            overflow-y: auto;
            padding: 10px; /* 添加内边距 */
            display: flex; /* 添加flex布局 */
            flex-direction: column; /* 垂直方向布局 */
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: center; /* 按钮居中对齐 */
        }

        .centered-table {
            width: 98%; /* 增加表格宽度 */
            margin: 0 auto; /* 表格居中 */
            flex: 1; /* 占满剩余空间 */
            display: flex; /* 添加flex布局 */
            flex-direction: column; /* 垂直方向布局 */
        }

        /* 表格样式优化 */
        .el-table {
            margin: 0 auto;
            table-layout: fixed; /* 添加固定表格布局 */
            width: 100%; /* 确保表格占满宽度 */
            height: 100% !important; /* 确保表格占满高度 */
        }
        
        .el-table th {
            background-color: #f5f7fa !important; /* 表头背景色 */
            color: #606266;
            font-weight: bold;
            text-align: center !important; /* 表头文字居中 */
            padding: 8px 0; /* 调整表头内边距 */
        }
        
        .el-table td {
            text-align: center; /* 单元格文字居中 */
            word-break: break-all; /* 文字过长时自动换行 */
            padding: 6px 0; /* 调整单元格内边距 */
        }

        .el-dialog {
            position: relative;
            margin: 0 auto 50px;
            background: #FFF;
            border-radius: 2px;
            -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
            box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
            box-sizing: border-box;
            width: 43%;
        }
        
        /* 封面相关样式 */
        .book-cover {
            width: 60px; /* 调整封面尺寸 */
            height: 90px;
            object-fit: cover;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            cursor: pointer;
            display: block;
            margin: 0 auto; /* 图片居中 */
        }
        
        .cover-placeholder {
            width: 60px; /* 调整封面尺寸 */
            height: 90px;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f0f0f0;
            border-radius: 4px;
            color: #909399;
            font-size: 12px;
            margin: 0 auto; /* 居中显示 */
        }
        
        .upload-demo {
            margin-top: 10px;
        }
        .nav-link {
            text-decoration: none;
            color: #409EFF;
            font-weight: bold;
            padding: 5px 10px;
            border-radius: 4px;
        }
        .nav-link:hover {
            background-color: #ecf5ff;
        }
    </style>
</head>
<body>
<div id="app" class="container">
    <div class="fixed-header">
        <!-- 添加图书按钮与浏览借阅记录按钮 -->
        <div style="margin-bottom: 10px;">
            <el-button type="primary" @click="showAddBookDialog">添加图书</el-button>
            <el-button type="info" @click="showBorrowHistory">浏览借阅记录</el-button>
            <a href="/book/overview" class="nav-link">图书管理</a>
            <a href="/user/management" class="nav-link">用户管理</a>
            <a href="/book/borrow" class="nav-link">借阅图书</a>
        </div>

        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="作者">
                <el-input v-model="searchForm.author" placeholder="作者"></el-input>
            </el-form-item>
            <el-form-item label="分类">
                <el-input v-model="searchForm.category" placeholder="分类"></el-input>
            </el-form-item>
            <el-form-item label="图书ID">
                <el-input v-model="searchForm.id" placeholder="图书ID"></el-input>
            </el-form-item>
            <el-form-item label="ISBN">
                <el-input v-model="searchForm.isbn" placeholder="ISBN"></el-input>
            </el-form-item>
            <el-form-item label="图书名">
                <el-input v-model="searchForm.title" placeholder="图书名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div class="content">
        <!-- 分页结果展示 -->
        <div class="centered-table">
            <el-table :data="books" style="width: 100%; height: 100%;" stripe border :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}" :fit="false">
                <!-- 添加封面列 -->
                <el-table-column label="封面" width="175" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.coverUrl" @click="previewCover(scope.row.coverUrl)">
                            <img :src="scope.row.coverUrl" class="book-cover" alt="封面">
                        </div>
                        <div v-else class="cover-placeholder">
                            暂无封面
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="id" label="图书ID" width="80" align="center"></el-table-column>
                <el-table-column prop="title" label="图书名" width="275" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column label="作者" width="200" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{ scope.row.author || '无作者信息' }}
                    </template>
                </el-table-column>
                <el-table-column label="分类" width="200" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{ scope.row.category || '无分类信息' }}
                    </template>
                </el-table-column>
                <el-table-column prop="copiesNumber" label="复本数" width="120" align="center"></el-table-column>
                <el-table-column prop="borrowedCopiesNumber" label="借出复本" width="120" align="center"></el-table-column>
                <el-table-column prop="borrowedNumber" label="借出次数" width="120" align="center"></el-table-column>
                <el-table-column label="操作" width="520" align="center">
                    <template slot-scope="scope">
                        <div class="action-buttons">
                            <el-button @click="showAddCopyDialog(scope.row)" type="primary" size="mini">添加复本</el-button>
                            <el-button @click="uploadCover(scope.row)" type="warning" size="mini">上传封面</el-button>
                            <el-button @click="editBook(scope.row)" type="success" size="mini">修改</el-button>
                            <el-button @click="removeBook(scope.row)" type="danger" size="mini">下架图书及复本</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <div class="fixed-footer">
        <!-- 分页组件 -->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
    </div>

    <!-- 添加图书对话框 -->
    <el-dialog title="添加图书" :visible.sync="addBookDialogVisible">
        <el-form :model="addBookForm">
            <el-form-item label="图书名" :label-width="formLabelWidth" required>
                <el-input v-model="addBookForm.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="作者" :label-width="formLabelWidth" required>
                <el-input v-model="addBookForm.author" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="分类" :label-width="formLabelWidth" required>
                <el-input v-model="addBookForm.category" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="ISBN" :label-width="formLabelWidth" required>
                <el-input v-model="addBookForm.isbn" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="出版日期" :label-width="formLabelWidth">
                <el-date-picker
                    v-model="addBookForm.publishedDate"
                    type="date"
                    placeholder="选择出版日期"
                    :picker-options="dateOptions"
                    value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <!-- 添加封面上传 -->
            <el-form-item label="图书封面" :label-width="formLabelWidth">
                <el-upload
                    class="upload-demo"
                    action="/books/upload/cover"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :show-file-list="false">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/bmp文件，且不超过10MB</div>
                </el-upload>
                <div v-if="addBookForm.coverUrl" style="margin-top: 10px; text-align: center;">
                    <img :src="addBookForm.coverUrl" style="width: 80px; height: 120px; object-fit: cover; border-radius: 4px;">
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addBookDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddBookForm">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 添加复本对话框 -->
    <el-dialog title="添加复本" :visible.sync="dialogVisible">
        <el-form :model="addCopyForm">
            <el-form-item label="图书编号" :label-width="formLabelWidth">
                <el-input v-model="addCopyForm.bookId" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="复本数量" :label-width="formLabelWidth">
                <el-input v-model="addCopyForm.quantity" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddCopyForm">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 修改图书对话框 -->
    <el-dialog title="修改图书" :visible.sync="editDialogVisible">
        <el-form :model="editBookForm">
            <el-form-item label="图书ID" :label-width="formLabelWidth">
                <el-input v-model="editBookForm.id" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="图书名" :label-width="formLabelWidth">
                <el-input v-model="editBookForm.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="作者" :label-width="formLabelWidth">
                <el-input v-model="editBookForm.author" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="分类" :label-width="formLabelWidth">
                <el-input v-model="editBookForm.category" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="ISBN" :label-width="formLabelWidth">
                <el-input v-model="editBookForm.isbn" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="出版日期" :label-width="formLabelWidth">
                <el-date-picker
                    v-model="editBookForm.publishedDate"
                    type="date"
                    placeholder="选择出版日期"
                    :picker-options="dateOptions"
                    value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <!-- 添加封面上传 -->
            <el-form-item label="图书封面" :label-width="formLabelWidth">
                <el-upload
                    class="upload-demo"
                    action="/books/upload/cover"
                    :on-success="handleEditUploadSuccess"
                    :on-error="handleUploadError"
                    :show-file-list="false">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/bmp文件，且不超过10MB</div>
                </el-upload>
                <div v-if="editBookForm.coverUrl" style="margin-top: 10px; text-align: center;">
                    <img :src="editBookForm.coverUrl" style="width: 80px; height: 120px; object-fit: cover; border-radius: 4px;">
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitEditBookForm">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 下架图书及复本对话框 -->
    <el-dialog title="下架图书及复本" :visible.sync="removeDialogVisible">
        <el-table :data="copies" style="width: 100%" :fit="true">
            <el-table-column prop="copyId" label="复本编号" width="180" align="center"></el-table-column>
            <el-table-column prop="name" label="借阅人" width="120" align="center"></el-table-column>
            <el-table-column prop="phone" label="电话号码" width="180" align="center"></el-table-column>
            <el-table-column prop="status" label="借阅状态" width="120" align="center"></el-table-column>
            <el-table-column label="操作" width="120" align="center">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.status === '在馆'" @click="removeCopy(scope.row)" type="danger"
                               size="mini">下架
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="removeDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmRemoveBook">下架该图书</el-button>
        </div>
    </el-dialog>
    
    <!-- 封面上传对话框 -->
    <el-dialog title="上传图书封面" :visible.sync="coverDialogVisible">
        <el-form>
            <el-form-item label="图书名" :label-width="formLabelWidth">
                <span>{{ currentBook.title }}</span>
            </el-form-item>
            <el-form-item label="当前封面" :label-width="formLabelWidth">
                <div v-if="currentBook.coverUrl" style="text-align: center;">
                    <img :src="currentBook.coverUrl" style="width: 100px; height: 150px; object-fit: cover; border-radius: 4px;">
                </div>
                <div v-else style="text-align: center; color: #909399;">暂无封面</div>
            </el-form-item>
            <el-form-item label="上传封面" :label-width="formLabelWidth">
                <el-upload
                    class="upload-demo"
                    action="/books/upload/cover"
                    :on-success="handleBookCoverUploadSuccess"
                    :on-error="handleUploadError"
                    :show-file-list="false"
                    style="text-align: center;">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/bmp文件，且不超过10MB</div>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="coverDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click.native="saveCoverChanges">保 存</el-button>
        </div>
    </el-dialog>
    
    <!-- 封面预览对话框 -->
    <el-dialog title="封面预览" :visible.sync="previewVisible" width="25%">
        <div style="display: flex; flex-direction: column; align-items: center;">
            <img :src="previewCoverUrl" style="max-width: 100%; max-height: 400px; object-fit: contain; border-radius: 4px;">
            <div style="margin-top: 15px;">
                <el-button type="primary" @click="downloadCover">下载封面</el-button>
            </div>
        </div>
    </el-dialog>
</div>

<!-- 引入Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- 引入Element UI -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!-- 引入Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchForm: {
                    author: '',
                    category: '',
                    id: '',
                    isbn: '',
                    title: ''
                },
                books: [],
                currentPage: 1,
                pageSize: 10,
                total: 0,
                dialogVisible: false,
                addCopyForm: {
                    bookId: '',
                    quantity: ''
                },
                formLabelWidth: '120px',
                editDialogVisible: false,
                editBookForm: {
                    id: '',
                    title: '',
                    author: '',
                    category: '',
                    isbn: '',
                    publishedDate: '',
                    coverUrl: '' // 封面URL字段
                },
                originalBookForm: {},
                removeDialogVisible: false,
                copies: [],
                selectedBookId: null,
                addBookDialogVisible: false,
                addBookForm: {
                    title: '',
                    author: '',
                    category: '',
                    isbn: '',
                    publishedDate: '',
                    coverUrl: '' // 封面URL字段
                },
                // 封面相关属性
                coverDialogVisible: false,
                currentBook: {},
                previewVisible: false,
                previewCoverUrl: '',
                tempCoverUrl: '',
                // 日期选择器配置
                dateOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now(); // 禁用当前日期之后的日期
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一个月前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一年前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 365);
                            picker.$emit('pick', date);
                        }
                    }]
                }
            };
        },
        methods: {
            onSearch() {
                this.fetchBooks();
            },
            fetchBooks() {
                const params = this.filterParams({
                    ...this.searchForm,
                    pageNo: this.currentPage, // 注意这里使用的是pageNo，不是pageNumber
                    pageSize: this.pageSize
                });
                
                axios.get('http://localhost:8091/books/page', {params})
                    .then(response => {
                        // 检查是否有数据并正确解析
                        if (response.data && response.data.data) {
                            const data = response.data.data;
                            // 确保数据格式正确
                            this.books = Array.isArray(data.list) ? data.list : [];
                            this.total = data.total || 0;
                            
                            // 调试输出
                            console.log('获取到的图书数据:', this.books);
                        } else {
                            console.error('接口返回数据格式不正确', response.data);
                            this.$message.error('获取图书数据失败: 数据格式不正确');
                        }
                    })
                    .catch(error => {
                        console.error('获取图书数据失败', error);
                        this.$message.error('获取图书数据失败: ' + (error.message || '未知错误'));
                    });
            },
            filterParams(params) {
                return Object.keys(params).reduce((acc, key) => {
                    if (params[key] !== '' && params[key] !== null && params[key] !== undefined) {
                        acc[key] = params[key];
                    }
                    return acc;
                }, {});
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchBooks();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchBooks();
            },
            showAddCopyDialog(row) {
                this.addCopyForm.bookId = row.id;
                this.addCopyForm.quantity = '';
                this.dialogVisible = true;
            },
            submitAddCopyForm() {
                axios.post('http://localhost:8091/books/copies', this.addCopyForm)
                    .then(response => {
                        if (response.data.status === "200") {
                            this.$message.success('复本添加成功');
                            this.dialogVisible = false;
                            // 刷新图书列表
                            this.fetchBooks();
                        } else {
                            this.$message.error('复本添加失败');
                        }
                    })
                    .catch(error => {
                        console.error('复本添加失败', error);
                        this.$message.error('复本添加失败');
                    });
            },
            editBook(row) {
                axios.get(`http://localhost:8091/books/${row.id}`)
                    .then(response => {
                        const data = response.data.data;
                        this.originalBookForm = {
                            id: data.id,
                            title: data.title,
                            author: data.author,
                            category: data.category,
                            isbn: data.isbn,
                            publishedDate: data.publishedDate,
                            coverUrl: data.coverUrl // 添加封面URL
                        };
                        this.editBookForm = {...this.originalBookForm};
                        this.editDialogVisible = true;
                    })
                    .catch(error => {
                        console.error('获取图书详细信息失败', error);
                        this.$message.error('获取图书详细信息失败');
                    });
            },
            submitEditBookForm() {
                const updatedFields = {};
                for (const key in this.editBookForm) {
                    if (this.editBookForm[key] !== this.originalBookForm[key]) {
                        updatedFields[key] = this.editBookForm[key];
                    }
                }
                if (Object.keys(updatedFields).length === 0) {
                    this.$message.warning('没有修改任何信息');
                    return;
                }
                updatedFields.id = this.editBookForm.id;
                axios.put('http://localhost:8091/books', updatedFields)
                    .then(response => {
                        if (response.data.status === "200") {
                            this.$message.success('图书修改成功');
                            this.editDialogVisible = false;
                            // 刷新图书列表
                            this.fetchBooks();
                        } else {
                            this.$message.error('图书修改失败');
                        }
                    })
                    .catch(error => {
                        console.error('图书修改失败', error);
                        this.$message.error('图书修改失败');
                    });
            },
            removeBook(row) {
                this.selectedBookId = row.id;
                axios.get(`http://localhost:8091/books/${row.id}`)
                    .then(response => {
                        const data = response.data.data;
                        this.copies = data.copies;
                        this.removeDialogVisible = true;
                    })
                    .catch(error => {
                        console.error('获取图书详细信息失败', error);
                        this.$message.error('获取图书详细信息失败');
                    });
            },
            removeCopy(copy) {
                axios.delete('http://localhost:8091/books/copies', {
                    params: {
                        copiesIds: copy.copyId.toString() // 将数组转换为逗号分隔的字符串
                    }
                })
                    .then(response => {
                        if (response.data.status === "200") {
                            this.$message.success('复本下架成功');
                            // 刷新复本信息
                            this.removeBook({id: this.selectedBookId});
                        } else {
                            this.$message.error('复本下架失败');
                        }
                    })
                    .catch(error => {
                        console.error('复本下架失败', error);
                        this.$message.error('复本下架失败');
                    });
            },
            confirmRemoveBook() {
                axios.delete('http://localhost:8091/books', {
                    params: {
                        bookIds: this.selectedBookId.toString()
                    }
                })
                    .then(response => {
                        if (response.data.status === "200") {
                            this.$message.success('图书下架成功');
                            this.removeDialogVisible = false;
                            // 刷新图书列表
                            this.fetchBooks();
                        } else {
                            this.$message.error(response.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('图书下架失败', error);
                        this.$message.error('图书下架失败');
                    });
            },
            showAddBookDialog() {
                this.addBookForm = {
                    title: '',
                    author: '',
                    category: '',
                    isbn: '',
                    publishedDate: '',
                    coverUrl: '' // 添加封面URL
                };
                this.addBookDialogVisible = true;
            },
            submitAddBookForm() {
                // 验证图书名、作者、分类、ISBN不为空
                if (!this.addBookForm.title || !this.addBookForm.author || !this.addBookForm.category || !this.addBookForm.isbn) {
                    this.$message.error('图书名、作者、分类、ISBN不能为空');
                    return;
                }

                axios.post('http://localhost:8091/books', this.addBookForm)
                    .then(response => {
                        if (response.data.status === "200") {
                            this.$message.success('图书添加成功');
                            this.addBookDialogVisible = false;
                            // 刷新图书列表
                            this.fetchBooks();
                        } else {
                            this.$message.error(response.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('图书添加失败', error);
                        this.$message.error('图书添加失败');
                    });
            },
            showBorrowHistory() {
                // 这里可以添加浏览借阅记录的逻辑
                //设置延时再跳转
                setTimeout(() => {
                    window.location.href = '/user/borrow/records';
                }, 100); // 100毫秒后跳转
            },
            // 添加封面相关方法
            handleUploadSuccess(response, file) {
                console.log('上传成功返回:', response);

                this.$message.success('封面上传成功');
                this.addBookForm.coverUrl = response.data;
                this.currentBook.coverUrl = response.data;
            },
            handleEditUploadSuccess(response, file) {
                console.log('编辑时上传成功返回:', response);

                this.$message.success('封面上传成功');

                this.editBookForm.coverUrl = response.data;
                this.currentBook.coverUrl = response.data;
            },
            handleBookCoverUploadSuccess(response, file) {
                console.log('单独上传封面返回:', response);

                if (response && response.status === "200" && response.data) {
                    this.$message.success('封面上传成功');
                    this.tempCoverUrl = response.data;
                    // 预览上传的封面
                    this.currentBook.coverUrl = response.data;
                    
                    // 调试信息
                    console.log('tempCoverUrl更新为:', this.tempCoverUrl);
                    console.log('currentBook.coverUrl更新为:', this.currentBook.coverUrl);
                } else {
                    console.error('上传响应异常:', response);
                    this.$message.error('封面上传失败: 响应格式异常');
                }
            },
            handleUploadError(err, file) {
                console.error('上传失败:', err);
                this.$message.error('封面上传失败: ' + (err.message || '网络错误'));
            },
            uploadCover(row) {
                axios.get(`http://localhost:8091/books/${row.id}`)
                    .then(response => {
                        if (response.data && response.data.data) {
                            this.currentBook = response.data.data;
                            this.tempCoverUrl = this.currentBook.coverUrl || '';
                            this.coverDialogVisible = true;
                        } else {
                            this.$message.error('获取图书详情失败: 数据格式不正确');
                        }
                    })
                    .catch(error => {
                        console.error('获取图书详情失败', error);
                        this.$message.error('获取图书详情失败: ' + (error.message || '网络错误'));
                    });
            },
            saveCoverChanges() {
                console.log('保存封面更改被调用');
                // 调试信息
                console.log('currentBook:', JSON.stringify(this.currentBook));
                console.log('tempCoverUrl:', this.tempCoverUrl);
                console.log('currentBook.coverUrl:', this.currentBook.coverUrl);
                
                // 检查currentBook是否有id
                if (!this.currentBook || !this.currentBook.id) {
                    this.$message.error('无法保存：图书ID无效');
                    return;
                }
                
                // 即使URL没有变化，也强制更新（解决可能的状态同步问题）
                //if (this.tempCoverUrl === this.currentBook.coverUrl) {
                //    console.log('封面URL没有变化，关闭对话框');
                //    this.coverDialogVisible = false;
                //    return;
                //}
                
                // 保存封面更改
                const updateData = {
                    id: this.currentBook.id,
                    coverUrl: this.currentBook.coverUrl
                };
                console.log('将发送更新请求:', JSON.stringify(updateData));
                
                axios.put('http://localhost:8091/books', updateData)
                    .then(response => {
                        console.log('封面更新响应:', response);
                        if (response.data.status === "200") {
                            this.$message.success('封面更新成功');
                            this.coverDialogVisible = false;
                            this.fetchBooks();
                        } else {
                            this.$message.error('封面更新失败: ' + (response.data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('封面更新失败', error);
                        this.$message.error('封面更新失败: ' + (error.message || '网络错误'));
                    });
            },
            previewCover(coverUrl) {
                if (coverUrl) {
                    this.previewCoverUrl = coverUrl;
                    this.previewVisible = true;
                } else {
                    this.$message.warning('该图书暂无封面');
                }
            },
            downloadCover() {
                if (this.previewCoverUrl) {
                    try {
                        window.open(`/books/download/cover?coverUrl=${encodeURIComponent(this.previewCoverUrl)}`, '_blank');
                    } catch (error) {
                        console.error('下载封面失败', error);
                        this.$message.error('下载封面失败: ' + (error.message || '未知错误'));
                    }
                } else {
                    this.$message.warning('没有可下载的封面');
                }
            }
        },
        created() {
            this.fetchBooks();
        }
    });
</script>
</body>
</html>
